# -*- coding: utf-8 -*-

import re
import logging

from datetime import datetime
from google.appengine.api import memcache
from google.appengine.api import images
#from getimageinfo import getImageInfo
from google.appengine.ext import db
from google.appengine.api import urlfetch

from models import Album

fashiongirlshost = 'http://fashiongirls.appwill.com/'

HOST = 'http://fashion-girls.appspot.com/'

def fetchContent(url, method=urlfetch.GET, data=None):
    logging.info("url:"+url)
    count = 1;
    while(count <= 3):
        response = None
        try:
            #urlfetch.REDIRECT_STATUSES = frozenset([httplib.SEE_OTHER])
            response = urlfetch.fetch(url=url, follow_redirects=False, method=method, payload=data)

            redirect_url = url
            redirect_counts = 0
            while redirect_counts < 4 and response and response.status_code in [301,302]:
                logging.info(str(count)+"--"+redirect_url+", status_code:"+str(response.status_code))
                if response.headers.has_key('location'):
                    redirect_url = response.headers['location']
                elif response.headers.has_key('Location'):
                    redirect_url = response.headers['Location']
                else:
                    raise Exception('Could not find location in headers: %r' % (response.headers,))

                global fashiongirlshost
                redirect_url = fashiongirlshost + redirect_url
                #logging.info("redirect url:"+redirect_url)
                response = urlfetch.fetch(url=redirect_url, follow_redirects=False)
                redirect_counts += 1

            url = redirect_url
        except:
            logging.info(str(count)+"--"+redirect_url+". Error!")
            logging.info(traceback.format_exc())
            count = count + 1
            continue

        logging.info(str(count)+"--"+url+", status_code:"+str(response.status_code))
        if response and response.status_code==200:
            return response.content
        count = count + 1

# #################################################################################################
def getMaxAlbumId():
    album = db.GqlQuery("SELECT * FROM Album ORDER BY shareid DESC").fetch(1)
    if(album and len(album)==1):
        return album[0].shareid+1
    else:
        return 1

def getAlbumById(shareid):
    albums = db.GqlQuery("SELECT * FROM Album WHERE shareid=:1", shareid).fetch(1)
    if(albums and len(albums)==1):
        return albums[0]
    else:
        return None

def getMaxAlbumEditorScore():
    album = db.GqlQuery("SELECT * FROM Album ORDER BY editor_score DESC").fetch(1)
    if(album and len(album)==1):
        return album[0].editor_score
    else:
        return 50

def getMinAlbumEditorScore():
    album = db.GqlQuery("SELECT * FROM Album ORDER BY editor_score").fetch(1)
    if(album and len(album)==1):
        return album[0].editor_score
    else:
        return 50

'''
def getTopEditorScoreAlbums(count, hide=0):
    albums = db.GqlQuery("SELECT * FROM Album ORDER BY editor_score DESC").fetch(count)
    return albums

def getTopScoreAlbums(count, hide=0):
    albums = db.GqlQuery("SELECT * FROM Album ORDER BY support_score DESC").fetch(count)
    return albums

def getTopLatestAlbums(count, hide=0):
    albums = db.GqlQuery("SELECT * FROM Album ORDER BY created_on DESC").fetch(count)
    return albums

def getTopDownloadedAlbums(count, hide=0):
    albums = db.GqlQuery("SELECT * FROM Album ORDER BY iphone_download_count DESC").fetch(count)
    return albums

def getTopPreviewAlbums(count, hide=0):
    albums = db.GqlQuery("SELECT * FROM Album ORDER BY preview_count DESC").fetch(count)
    return albums
'''

def getTopEditorScoreAlbums(count, hide=0):
    if hide == 0:
        albums = db.GqlQuery("SELECT * FROM Album WHERE hide=:1 ORDER BY editor_score DESC", hide).fetch(count)
        return albums
    else:
        albums = db.GqlQuery("SELECT * FROM Album ORDER BY editor_score DESC").fetch(count)
        return albums
    
def getTopScoreAlbums(count, hide=0):
    if hide == 0:
        albums = db.GqlQuery("SELECT * FROM Album WHERE hide=:1 ORDER BY support_score DESC", hide).fetch(count)
        return albums
    else:
        albums = db.GqlQuery("SELECT * FROM Album ORDER BY support_score DESC").fetch(count)
        return albums

def getTopLatestAlbums(count, hide=0):
    if hide == 0:
        albums = db.GqlQuery("SELECT * FROM Album WHERE hide=:1 ORDER BY created_on DESC", hide).fetch(count)
        return albums
    else:
        albums = db.GqlQuery("SELECT * FROM Album ORDER BY created_on DESC").fetch(count)
        return albums

def getTopDownloadedAlbums(count, hide=0):
    if hide == 0:
        albums = db.GqlQuery("SELECT * FROM Album WHERE hide=:1 ORDER BY iphone_download_count DESC", hide).fetch(count)
        return albums
    else:
        albums = db.GqlQuery("SELECT * FROM Album ORDER BY iphone_download_count DESC").fetch(count)
        return albums

def getTopPreviewAlbums(count, hide=0):
    if hide == 0:
        albums = db.GqlQuery("SELECT * FROM Album WHERE hide=:1 ORDER BY preview_count DESC", hide).fetch(count)
        return albums
    else:
        albums = db.GqlQuery("SELECT * FROM Album ORDER BY preview_count DESC").fetch(count)
        return albums

def addAlbumFromURL(url):
    if url is None or url.strip()=='':
        return None
    
    url = url.strip()
    
    index = url.find('#')
    if index>=0:
        url = url[0: index]

    if not url.startswith('http://picasaweb.google.com') and not url.startswith('http://www.flickr.com'):
        return None
    
    service_url = '%salbumXMLFromPicasaLink/?pass=34lkasmfouq84adskfn&url=%s'%(fashiongirlshost, url)
    
    xml_content = fetchContent(service_url)
    
    xml_content = unicode(xml_content, 'utf-8', 'ignore')

    #logging.info(xml_content)

    '''
    #xml_content.encode('utf-8', 'ignore')
    #logging.info(xml_content)

    xml_dom = parseString(xml_content.encode('utf-8', 'ignore'))

    pictures = xml_dom.getElementsByTagName('picture')
    picture_count = len(pictures)

    album = xml_dom.getElementsByTagName('album')[0]
    #print 'album.childNodes:', len(album.childNodes)

    picasa_link = ''
    title = ''
    desc = ''
    provider = ''
    cover = ''

    for node in album.childNodes:
        if node.nodeName == 'title':
            if node.childNodes and len(node.childNodes)>0:
                title = node.childNodes[0].nodeValue
                logging.info( title )
        elif node.nodeName == 'description':
            if node.childNodes and len(node.childNodes)>0:
                desc = node.childNodes[0].nodeValue
                logging.info( desc )
        elif node.nodeName == 'provider':
            if node.childNodes and len(node.childNodes)>0:
                provider = node.childNodes[0].nodeValue
                logging.info( provider )
        elif node.nodeName == 'cover':
            if node.childNodes and len(node.childNodes)>0:
                cover = node.childNodes[0].nodeValue
                logging.info( cover )
        elif node.nodeName == 'source':
            if node.childNodes and len(node.childNodes)>0:
                picasa_link = node.childNodes[0].nodeValue
                logging.info( picasa_link )
    '''

    picture_count = xml_content.count(u'<picture>')
    title, desc, picasa_link, cover, provider = getMetaDataFromAlbumXMLContent(xml_content)
    #logging.info(title)
    #logging.info(desc)
    #logging.info(provider)
    #logging.info(picasa_link)
    #logging.info(cover)

    shareid = getMaxAlbumId()
    max_editor_score = getMaxAlbumEditorScore()
    
    xml_url = u'%s%d/'%(HOST, shareid)
    xml_content = xml_content.replace(u'^ALBUM_XML_URL_APPWILLFASHIONGIRLS$', xml_url)

    #logging.info(provider)
    #logging.info(toUTF8(provider))
    #logging.info(unicode(title.encode('utf-8', 'ignore'), 'gbk'))
    #logging.info(toUTF8(desc))
    #logging.info(toUTF8(xml_content))

    album = Album(shareid=shareid,
        picasa_link=url,
        provider=provider,
        cover=cover,
        title=title,
        desc=desc,
        picture_count=picture_count,
        xml_url=xml_url,
        xml=xml_content,
        support_score=100,
        preview_count=0,
        download_count=0,
        iphone_download_count=0,
        editor_score=max_editor_score,
        hide=0)

    album.put()
    
    return album
    

def getMetaDataFromAlbumXMLContent(xml_content):
    picasa_link = ''
    title = ''
    desc = ''
    provider = ''
    cover = ''

    re_str = r'''<title><\!\[CDATA\[(.*?)\]\]></title>'''
    match_obj = re.search(re_str, xml_content)
    if match_obj:
        title = match_obj.group(1)

    re_str = r'''<description><\!\[CDATA\[(.*?)\]\]></description>'''
    match_obj = re.search(re_str, xml_content)
    if match_obj:
        desc = match_obj.group(1)

    re_str = r'''<source><\!\[CDATA\[(.*?)\]\]></source>'''
    match_obj = re.search(re_str, xml_content)
    if match_obj:
        picasa_link = match_obj.group(1)

    re_str = r'''<provider><\!\[CDATA\[(.*?)\]\]></provider>'''
    match_obj = re.search(re_str, xml_content)
    if match_obj:
        provider = match_obj.group(1)

    re_str = r'''<cover><\!\[CDATA\[(.*?)\]\]></cover>'''
    match_obj = re.search(re_str, xml_content)
    if match_obj:
        cover = match_obj.group(1)

    return title, desc, picasa_link, cover, provider